package client.comm.baoding.fragment

import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.util.TypedValue
import android.view.View
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import client.comm.commlib.base.BaseFragment
import client.comm.commlib.base.SimpleTextWatcher
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.Util
import client.comm.commlib.widget.EmptyLayout
import client.comm.baoding.R
import client.comm.baoding.adapter.NewBuyCartAdapter
import client.comm.baoding.api.bean.BuyCartRet
import client.comm.baoding.api.bean.ShopingBean
import client.comm.baoding.databinding.FragmentTabthreeBinding
import client.comm.baoding.ui.ConfirmOrderActivity
import client.comm.baoding.ui.GoodsDetailActivity
import client.comm.baoding.ui.vm.MainViewModel
import kotlinx.coroutines.flow.collect
import java.math.BigDecimal
import java.util.*

class TabThreeFragment : BaseFragment<FragmentTabthreeBinding, MainViewModel>() {

    override fun getViewId(): Int {
        return R.layout.fragment_tabthree
    }

    override fun initViewModel(): MainViewModel = createViewModel()
    val adapterCart: NewBuyCartAdapter by lazy {
        NewBuyCartAdapter(requireActivity(), mImgLoader).apply {

            changeNumItem = { b, n ->
                var lastNum = 1
                try {
                    if (!TextUtils.isEmpty(b.selectNum.get())) {
                        lastNum = b.selectNum.get()!!.toInt() + n
                    }
                } catch (e: Exception) {
                }

                if (lastNum < 1)
                    lastNum = 1
                b.selectNum.set("${lastNum}")
            }

            textWatcher = object : SimpleTextWatcher() {
                override fun afterTextChanged(s: Editable?) {
                    super.afterTextChanged(s)
                    updatePrice(adapterCart)
                }
            }

            changeCheckItem = {
                it.isCheck.set(!it.isCheck.get()!!)
                updataAllCheck()
                updatePrice(adapterCart)
            }

            detailItem = {
                context.startActivity(Intent(context, GoodsDetailActivity::class.java).apply {
                    putExtra("goodsId", "${it.goods_id}")
                })
            }

            addLoadStateListener {
                when (it.refresh) {
                    is LoadState.NotLoading -> {
                        if (itemCount == 0) {
                            binding.emptyLayout.errorType = EmptyLayout.NODATA
                        } else {
                            binding.emptyLayout.visibility = View.GONE
                        }
                        updatePrice(this)
                    }
                    is LoadState.Loading -> {
                        if (itemCount == 0) {
                            binding.emptyLayout.errorType = EmptyLayout.NETWORK_LOADING
                        }
                    }
                    is LoadState.Error -> {
                        if (itemCount == 0)
                            binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                        toast((it.refresh as LoadState.Error).error.message)
                    }
                }
            }
        }
    }

    override fun initWidget() {
        binding.vm = viewModel
        binding.event = this
        binding.statusBar.post {
            val h = Util.getStatusBarHeight(requireContext())
            val p = binding.statusBar.layoutParams
            p.height = h
            binding.statusBar.layoutParams = p
            Util.setBg(resources!!.getColor(R.color.main_bg), requireActivity().window)
            val controller = ViewCompat.getWindowInsetsController(binding.root)
            controller?.isAppearanceLightStatusBars = true
        }
        binding.recyclerView.adapter = adapterCart
        binding.emptyLayout.setOnClickListener {
            adapterCart.refresh()
        }

        lifecycleScope.launchWhenCreated {
            viewModel.buyCart().collect {

                viewModel.isCheckAll.value = false
                viewModel.isEditMode.value = "编辑"
                viewModel.isEditModeVal.value = true
                adapterCart.submitData(it)
            }
        }
        viewModel.delRet.observe(this, {
            it?.apply {
                if (it.isSuccess) {
                    toast("成功")
                    viewModel.delRet.value = null
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_LOADING
                    adapterCart.refresh()

                }
            }
        })

    }

    fun del() {
        val list = ArrayList<BuyCartRet.Shopping>()

        for (e in 0..(adapterCart.itemCount - 1)) {
            val i = adapterCart.getItemObj(e)
            i?.let {
                if (it.isCheck.get() == true) {
                    list.add(it)
                }
            }
        }

        if (list.size == 0) {

            toast("请选中商品后再提交")
            return
        }
        viewModel.delCart(list)
    }

    fun updatePrice(adapterCart: NewBuyCartAdapter) {
        var number: BigDecimal = BigDecimal(0)
        var integral: BigDecimal = BigDecimal(0)
        for (e in 0..adapterCart.itemCount - 1) {

            val b = adapterCart.getItemObj(e)
            b?.let {

                if (it.isCheck.get() == true && !TextUtils.isEmpty(it.selectNum.get())) {
                    var num = 0;
                    try {
                        if (!TextUtils.isEmpty(it.selectNum.get())) {
                            num = it.selectNum.get()!!.toInt()
                        }
                    } catch (e: Exception) {
                    }
                    if (num > 0) {
                        number = number.add(BigDecimal(num).multiply(BigDecimal(b.price)))
                        integral = integral.add(BigDecimal(num).multiply(BigDecimal(b.integral)))

                    }
                }

            }
        }
//        binding.price = "${number.toDouble()}"

        binding.commPriceIntegral.apply {
            comm_price_integral(tvPriceUnit,tvPrice,number.toDouble(),tvIntegral,integral.toDouble(),tvIntegralDesc)
        }

    }


    /**
     * 通用商品价格和积分格式化
     */
    fun comm_price_integral(
        tvPriceUnit: TextView,
        tvPrice: TextView,
        price: Double,
        tvIntegral: TextView,
        integral: Double,
        tvIntegralDesc: TextView
    ) {
        var is_price_show: Boolean = false
        var is_integral_unit_show: Boolean = false

        if (price > 0) {
            tvPrice.text = "${price}"
            is_price_show = true
            if (integral > 0) {
                tvIntegral.text = "+${integral}" //+ "积分"
                is_integral_unit_show = true
            } else {
                tvIntegral.text = ""
                is_integral_unit_show = false
            }

        } else {
            tvPrice.text = ""
            is_price_show = false
            if (integral > 0) {
                tvIntegral.text = "" + integral //+ "积分"
                is_integral_unit_show = true
            } else {
                tvIntegral.text = ""
                is_integral_unit_show = false
            }
        }

        if (is_price_show) {
            tvPriceUnit.visibility = View.VISIBLE
        } else {
            tvPriceUnit.visibility = View.GONE
        }

        if (is_integral_unit_show) {
            tvIntegralDesc.visibility = View.VISIBLE
        } else {
            tvIntegralDesc.visibility = View.GONE
        }

    }

    //改变全选中状态
    fun changeAllCheck() {
        val bbb = !viewModel.isCheckAll.value!!
        viewModel.isCheckAll.value = bbb
        for (e in 0..adapterCart.itemCount - 1) {
            val i = adapterCart.getItemObj(e)
            i?.let {
                it.isCheck.set(bbb)
            }
        }
        updatePrice(adapterCart)
    }

    fun updataAllCheck() {
        var bbb = true
        for (e in 0..adapterCart.itemCount - 1) {
            val i = adapterCart.getItemObj(e)
            i?.let {
                if (it.isCheck.get() == false) {
                    bbb = false
                }
            }
        }
        viewModel.isCheckAll.value = bbb
    }

    fun editAll() {//改变编辑模式
        val bbb = false
        viewModel.isCheckAll.value = bbb
        for (e in 0..adapterCart.itemCount - 1) {
            val i = adapterCart.getItemObj(e)
            i?.let {
                it.isCheck.set(bbb)
            }
        }
        viewModel.isEditMode.value = if (viewModel.isEditMode.value!!.equals("编辑")) "取消" else "编辑"
        viewModel.isEditModeVal.value =
            if (viewModel.isEditMode.value!!.equals("编辑")) true else false
        updatePrice(adapterCart)
    }

    //确认订单
    fun ok() {
        val list = ArrayList<ShopingBean>()
        for (e in 0..adapterCart.itemCount - 1) {
            val i = adapterCart.getItemObj(e)
            i?.let {
                var num: Int = 0
                try {
                    it.selectNum?.get()?.apply {
                        num = this.toInt()
                    }
                } catch (e: Exception) {
                }

                if (it.isCheck.get() == true && num > 0) {
                    it.num = num
                    val bbb = ShopingBean(
                        goods_id = it.goods_id,
                        goods_img = it.goods_img,
                        name = it.name,
                        old_price = it.old_price,
                        price = it.price,
                        lpq_price = it.lpq_price,
                        shopping_id = "${it.shopping_id}",
                        store_id = "${it.store_id}",
                        num = it.num,
                        integral = it.integral,
//                        integral_f = it.integral_f,
                        price_r = it.price_r,
                        create_time = it.create_time,
                        sku = it.sku
                    )
                    list.add(bbb)
                }
            }
        }

        if (list.size == 0) {
            toast("请选中商品后再提交")
        } else {
            startActivity(
                Intent(
                    requireActivity(),
                    ConfirmOrderActivity::class.java
                ).apply {
                    putExtra("list", list)
                })
        }
    }
}